import ssl
import OpenSSL
import datetime
from pytz import timezone

'''
date: 2022-11-18 21:22:14
参考: https://knktc.com/2021/06/20/use-python-to-check-ssl-expiry-date/
安装依赖库: pip install pyOpenSSL
'''

SRC_TZ = 'UTC'
DST_TZ = 'Asia/Shanghai'

def load_ssl_date(dt_string, pattern='%Y%m%d%H%M%SZ'):
    """ convert ssl date from string to datetime obj """
    src_tz = timezone(SRC_TZ)
    dst_tz = timezone(DST_TZ)
    dt = src_tz.localize(datetime.datetime.strptime(dt_string, pattern))
    return dt.astimezone(tz=dst_tz)

def get_domain_exp_date(host, port=443):
    cert = ssl.get_server_certificate((host, port))
    x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
    utctime = x509.get_notAfter().decode()
    exp_date = load_ssl_date(utctime)
    return exp_date


def main():
    domain = 'www.baidu.com'
    exp_date = get_domain_exp_date(domain)
    print(domain, exp_date)

if __name__ == '__main__':
    main()
